<?php
/**
 * Created by PhpStorm.
 * User: tony
 * Date: 2018/6/4
 * Time: 11:20
 */

namespace app\modules\v1\controllers;

use app\config\Status;
use app\models\Part;
use app\modules\v1\controllers\parent\ParentController;
use yii\data\ActiveDataProvider;

class PartController extends ParentController
{
    public function actionIndex() {
        $params = \Yii::$app->request->getQueryParams();
        $query = Part::find()->with('user');
        $query->andWhere(['>', 'id', 1]);
        $pageSize = 10;
        if(isset($params['pageSize'])){
            $pageSize = (int)$params['pageSize'];
        }
        return new ActiveDataProvider([
            // 使用with方法实现贪加载
            'query' => $query,
            // 分页信息
            'pagination' => [
                'pageSize' => $pageSize,
            ],
            // 排序信息
            'sort' => [
                'defaultOrder' => [
                    'id' => SORT_DESC,
                ]
            ],
        ]);
    }


    public function actionView() {
        $params = \Yii::$app->request->getQueryParams();
        $result = Part::findOne(['id' => $params['id']]);
        return $result;
    }

    /**
     * @throws \yii\base\InvalidConfigException
     */
    public function actionCreate() {
        $data = \Yii::$app->request->getBodyParams();
        $model = new Part();
        $model->load($data, '');
        $model->creater= \Yii::$app->user->id;
        $model->create_at = time();
        if ($model->save()) {
            return [
                'bCode' => Status::SUCCESS,
                'bData' => $model,
            ];
        }

        return [
            'bCode' => Status::SUCCESS,
            'bData' => $model->errors,
        ];
    }

    /**
     * @throws \yii\base\InvalidConfigException
     */
    public function actionUpdate() {
        $data = \Yii::$app->request->getBodyParams();
        $model = Part::findOne(['id' => $data['id']]);
        $model->load($data, '');
        $model->updater = \Yii::$app->user->id;
        $model->update_at = time();

        if ($model->save()) {
            return [
                'bCode' => Status::SUCCESS,
                'bData' => $model,
            ];
        }

        return [
            'bCode' => Status::SUCCESS,
            'bData' => $model->errors,
        ];
    }

    /**
     * @throws \Throwable
     * @throws \yii\base\InvalidConfigException
     */
    public function actionDelete() {
        $data = \Yii::$app->request->getBodyParams();
        $model = Part::findOne(['id' => $data['id']]);
        if ($model) {
            $model->delete();
            return [
                'bCode' => Status::SUCCESS,
                'bData' => $model
            ];
        } else {
            return [
                'bCode' => Status::FAIL,
                'bData' => '改角色不存在'
            ];
        }

    }
}